package com.example.uCenter.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.uCenter.common.Code;
import com.example.uCenter.common.Paging;
import com.example.uCenter.common.Result;
import com.example.uCenter.user.entity.User;
import com.example.uCenter.user.mapper.UserMapper;
import com.example.uCenter.user.service.IUserService;
import com.example.uCenter.utils.SaltUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 服务实现类
 *
 * @author xxs
 * @since 2022-08-27 08:20:38
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private BlacklistServiceImpl blacklist;
    @Autowired
    private FansServiceImpl fans;
    @Autowired
    private ImageServiceImpl image;
    @Autowired
    private InformationServiceImpl information;
    @Autowired
    private LoginRecordsServiceImpl loginRecords;
    @Autowired
    private PersonalDataServiceImpl personalData;
    @Autowired
    private RegisterServiceImpl register;
    @Autowired
    private TokenServiceImpl token;

    /**
     * 账号密码登录
     *
     * @return
     */
    @Override
    public Result Login(String userName, String password) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_name", userName);
        User user1 = getBaseMapper().selectOne(qw);

        String salt = user1.getSalt();
        String pwdSalt = SaltUtil.AddSalt(salt, password);

        if (pwdSalt.equals(user1.getPassword()) && user1.getStatus() == 1 && user1.getIsDeleted() == 0) {
            user1.setStatus(0);
            return new Result(user1, Code.GET_OK, "查询数据成功");
        } else {
            return new Result(false, Code.GET_ERROR, "查询数据失败");
        }
    }

    /**
     * 分页查询
     * hhl
     *
     * @param current 当前页
     * @param size    每页大小
     * @return 类型 Result 查询成功返回20091返回单表中所有当前页的结果集、总页数、总记录数、当前页、每页大小、提示语句
     */
    @Override
    public Result findPaging(Integer current, Integer size) {
        IPage<User> page = new Page<>(current, size);
        getBaseMapper().selectPage(page, null);
        long pages = page.getPages();
        List<User> records = page.getRecords();
        System.out.println("测试点一");
        long total = page.getTotal();
        Result result = new Result();
        Paging paging = new Paging(pages, records, total, current, size);
        result.setCode(Code.GET_ALL_OK);
        result.setData(paging);
        result.setMsg("共" + page.getPages() + "页、" + page.getTotal() + "条记录，第" + current + "页查询成功，还剩下" + (page.getPages() - current) + "页");
        System.out.println("测试点二");
        return result;
    }

    /**
     * 服务实现
     *
     * @author yzh
     * @since 2022-08-29
     */
    @Override
    public List<User> selectAllByUser() {
        return getBaseMapper().selectList(null);
    }

    /**
     * 新增
     *
     * @param user
     * @return
     */
    @Override
    public boolean RegisterByUserAdd(User user) {
        //begin
        boolean isSuccess = false;
        int insert = getBaseMapper().insert(user);
        System.out.println(insert);
        if (insert == 1) {
            isSuccess = true;
        }
        // int i = 9/0;
        // end
        return isSuccess;
    }

    /**
     * 查询用户Id最大值
     *
     * @return
     */
    @Override
    public int selectUserMaxId() {
        return getBaseMapper().selectMaxId();
    }

    /**
     * 单个逻辑删除
     *
     * @param userId
     * @return
     */
    @Override
    public Result RemoveUser(Integer userId) {
        Result result = new Result(false, Code.DELETE_ERROR, "数据删除失败！！！");
        try {
            int i = getBaseMapper().deleteById(userId);
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("user_id", userId);
            if (i > 0) {
                token.remove(qw);
                blacklist.remove(qw);
                fans.remove(qw);
                register.remove(qw);
                personalData.remove(qw);
                loginRecords.remove(qw);
                image.remove(qw);
                information.remove(qw);
                result.setData(true);
                result.setCode(Code.DELETE_OK);
                result.setMsg("数据删除成功！！！");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

    }

    /**
     * 批量逻辑删除
     *
     * @param userIds
     * @return
     */
    @Override
    public Result RemoveUserAll(List<Integer> userIds) {
        Result result = new Result(false, Code.DELETE_ALL_ERROR, "数据全部删除失败！！！");
        QueryWrapper qw = new QueryWrapper<>();
        if (getBaseMapper().deleteBatchIds(userIds) > 0) {
            for (Integer userId : userIds) {
                qw.eq("user_id", userId);
                qw.or();
            }
            token.remove(qw);
            blacklist.remove(qw);
            fans.remove(qw);
            register.remove(qw);
            personalData.remove(qw);
            loginRecords.remove(qw);
            image.remove(qw);
            information.remove(qw);
            result.setData(true);
            result.setCode(Code.DELETE_ALL_OK);
            result.setMsg("数据全部删除成功！！！");
        }
        return result;
    }

    /**
     * 添加数据
     *
     * @param user
     * @return
     */
    @Override
    public Result AddUser(User user) {
        Result result = new Result(false, Code.SAVE_OK, "数据添加失败！！！");

        // 没有加盐则随机生成盐
        if (Objects.isNull(user.getSalt())) {
            user.setSalt(RandomStringUtils.randomAlphabetic(16));
        }

        // 密码加盐加密
        String pwd = SaltUtil.AddSalt(user.getSalt(), user.getPassword());
        user.setPassword(pwd);
        // id没有，则id赋值为最大+1
        if (Objects.nonNull(user.getUserId())) {
            Integer maxId = getBaseMapper().selectMaxId();
            user.setUserId(maxId + 1);
        }
        // 添加数据并判断
        if (getBaseMapper().insert(user) > 0) {
            result.setData(true);
            result.setCode(Code.SAVE_OK);
            result.setMsg("数据添加成功！！！");
        }
        return result;
    }

    public Result findToken(String user) {
        return null;
    }
}
